package rwlivbk.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import rwlivbk.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import rwlivbk.common.TokenExpiredException;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理 SpringMVC 参数校验不正确
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex) {
        log.warn("[methodArgumentNotValidExceptionExceptionHandler]", ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        assert fieldError != null; // 断言，避免告警
        return CommonResult.error(400, String.format("请求参数不正确:%s", fieldError.getDefaultMessage()));
    }

//    @ExceptionHandler(TokenExpiredException.class)
//    public CommonResult<?> handleTokenExpiredException(TokenExpiredException ex) {
//        log.warn("[handleTokenExpiredException]", ex);
////        FieldError fieldError = ex.getBindingResult().getFieldError();
////        assert fieldError != null; // 断言，避免告警
//        return CommonResult.error(402, String.format("Token已过期:%s"));
//    }

    @ExceptionHandler(TokenExpiredException.class)
    public ResponseEntity<?> handleTokenExpiredException(TokenExpiredException ex) {
        Map<String, Object> response = new HashMap<>();
        response.put("error", "Unauthorized");
        response.put("message", ex.getMessage());
        return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
    }
}
